package com.efounder.agency.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.activity.TabBottomActivity;
import com.efounder.activity.TabBottomActivity.TabBottomActivityResultListener;
import com.efounder.chat.adapter.TaskListAdapter;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.model.Task;
import com.efounder.chat.model.TaskRefreshEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.comp.shoppingcar.DividerItemDecoration;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.http.EFHttpRequest;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AppContext;
import com.efounder.util.SetFMTEnvironmetVariableValueUtil;
import com.pansoft.xmlparse.FormatSet;
import com.pansoft.xmlparse.MobileFormatUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import static com.efounder.frame.activity.EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR;


/**
 * 待办 最新
 *
 * @author long 2015年9月2日13:56:45
 */
@SuppressLint({"InflateParams", "HandlerLeak"})
public class AgentFgNewTG extends BaseFragment implements TabBottomActivityResultListener {
    private static final String TAG = "AgentFgNew";
    private static final String resPath = AppConstant.APP_ROOT + "/res/unzip_res/Image/";
    //	private static final String URL = "http://192.168.248.220:58681/GWTServer/OpenAPIService/" +
//			"TJFlowTask?RequestParam={Param:{RESR_STATUS:%27pending%27}}";
    //private static final String URL1 = "http://zsytght.solarsource.cn:9692/ZSYTGHT/OpenAPIService/" +
    private static final String BASEURL = EnvironmentVariable.getProperty("OSPTaskURL", "http://zsytghr43935.solarsource.cn:9692");
    private static final String PROJECT_PATH = EnvironmentVariable.getProperty("OSPTaskProjectPath", "HT");
    //测试
//	private static final String URL1 = "http://zsytghr43935.solarsource.cn:9692/HT/OpenAPIService/" +
    private static final String URL1 = BASEURL + "/OpenAPIService/" +
            //正式
//    private static final String URL1 = "http://zsytght.solarsource.cn:9692/ZSYTGHT/OpenAPIService/" +
            "TJFlowTask?RequestParam={Param:{Product:'HTGLXT',RESR_STATUS:'all',IS_PAGING='1',PAGING_START=";
    private static String URL2 = ",PAGING_SHOWNUM=10,UserName='" + EnvironmentVariable.getUserName() + "'}}";
    private static final int UPDATED = 1;
    private RecyclerView mRecyclerView;
    private boolean hasLoadData = false;
    private int page = 0;//加载任务的页码
    private List<Task> mData;
    private FormatSet formatSet;
    TaskListAdapter adapter;
    RelativeLayout include;
    ScrollView linearLayout;
    StubObject stubObject;
    private SmartRefreshLayout mSrl;

    private int taskDataItem0, taskDataItem1, taskDataItem2;//中油铁工的角标
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            getTaskData(false);
        }
    };

    public AgentFgNewTG() {
        super();
    }

    @SuppressLint("ValidFragment")
    public AgentFgNewTG(StubObject _stubObject) {
        super();
        stubObject = _stubObject;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof TabBottomActivity) {
            TabBottomActivity tabBottomActivity = (TabBottomActivity) activity;
            tabBottomActivity.setOnTabBottomActivityResultListener(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//		if (isAlone() && !hasLoadData) {
//			new NewLoadAsyncTask().execute();
//		}
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fg_new_agent_ui_withtilte, null);

        mSrl = (SmartRefreshLayout) root
                .findViewById(R.id.srl);
        mSrl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getTaskData(true);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getTaskData(false);
                getTGBadgeNum();//中铁工专用，其他请注释掉
            }
        });
//        铁工专用  上拉和下拉
        // pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
//        //只允许下拉
//        pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        include = (RelativeLayout) root.findViewById(R.id.include);
        // 判断fragment是否是单独的
        if (isAlone()) {
            include.setVisibility(View.VISIBLE);
        } else {
            include.setVisibility(View.GONE);
        }
        EventBus.getDefault().register(this);
        include.setBackgroundResource(R.color.chat_red);
        TextView title = (TextView) root.findViewById(R.id.fragmenttitle);
        title.setText("任务中心");
        title.setTextColor(Color.WHITE);
        LinearLayout leftbacklayout = (LinearLayout) root
                .findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);
        leftbacklayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//				AgentFgNew.this.getFragmentManager().popBackStack();
                getActivity().finish();
            }
        });
        formatSet = MobileFormatUtil.getInstance().getFormatSet();

        mData = new ArrayList<>();
        //在每次这个页面第一次加载的时候，需要将badgeNum设为0，防止网络问题加载不出数据，但是badgeNum还是之前数据的问题
        EnvironmentVariable.setProperty("Badge_Task_Pending", 0 + "");
        EventBus.getDefault().post(new UpdateBadgeViewEvent(-3 + "", (byte) 2));
        getTGBadgeNum();//中铁工专用，其他请注释掉
        getTaskData(false);
        Button buttonRight = (Button) root.findViewById(R.id.closeButton);
        buttonRight.setVisibility(View.INVISIBLE);
        buttonRight.setBackgroundResource(R.drawable.rightmenu);
        buttonRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });
        linearLayout = (ScrollView) root
                .findViewById(R.id.fg_new_agent_linear_layout);

        mRecyclerView = (RecyclerView) root.findViewById(R.id.recyclerView);

        super.onCreateView(inflater, container, savedInstanceState);
        adapter = new TaskListAdapter(getActivity(), mData);
        adapter.setOnItemClickLitener(new TaskListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Map<String, Object> map = new HashMap<String, Object>();
//                EnvironmentVariable.setProperty("TaskDetail_FLOW_ID", null);
//                EnvironmentVariable.setProperty("task_flowId", mData.get(position).getId());
//                EnvironmentVariable.setProperty("task_header", mData.get(position).getTitle());
//                EnvironmentVariable.setProperty("task_avatar", "");
//                EnvironmentVariable.setProperty("task_badgeValue", String.valueOf(mData.get(position).getTodoNum()));
                map.put("TaskDetail_FLOW_ID", null);
                map.put("task_flowId", mData.get(position).getId());
                map.put("task_header", mData.get(position).getTitle());
                map.put("task_avatar", "");
                map.put("task_badgeValue", String.valueOf(mData.get(position).getTodoNum()));

                if (position != 0 && position != 1) {
                    Map<String, Object> fmtMap = SetFMTEnvironmetVariableValueUtil.setFmtEnvironmentValue(getContext(), mData.get(position).getId());
                    map.putAll(fmtMap);
//                    SetFMTEnvironmetVariableValueUtil.setFmtEnvironmentValue(getContext(), mData.get(position).getId());
                }
                //中铁工专用，其他请注释掉
                if (position == 0) {
                    try {
                        Bundle bundle = new Bundle();
                        bundle.putString("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                        bundle.putString("userName", EnvironmentVariable.getUserName());
//						bundle.putString(EFTransformFragmentActivity.EXTRA_TITLE_NAME,"测试");
//						bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_RIGHT_VISIBILITY,View.INVISIBLE);
                        bundle.putBoolean(EXTRA_HIDE_TITLE_BAR, true);
                        EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("sy.petrochina.zsytg.fragment.TaskMainFragment"), bundle);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } else if (position == 1) {
                    try {
                        Bundle bundle = new Bundle();
                        bundle.putString("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                        bundle.putString("userName", EnvironmentVariable.getUserName());
//						bundle.putString(EFTransformFragmentActivity.EXTRA_TITLE_NAME,"测试");
//						bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_RIGHT_VISIBILITY,View.INVISIBLE);
                        bundle.putBoolean(EXTRA_HIDE_TITLE_BAR, true);
                        EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("sy.petrochina.zsytg.fragment.OAMainFragment"), bundle);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } else if (position == 2) {
                    try {
                        Bundle bundle = new Bundle();
                        bundle.putString("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
                        bundle.putString("userName", EnvironmentVariable.getUserName());
//						bundle.putString(EFTransformFragmentActivity.EXTRA_TITLE_NAME,"测试");
//						bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_RIGHT_VISIBILITY,View.INVISIBLE);
                        bundle.putBoolean(EXTRA_HIDE_TITLE_BAR, true);
                        EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("sy.petrochina.zsytg.fragment.ZJTaskMainFragment"), bundle);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        if (map.get("hfmt") == null) {
                            Toast.makeText(getContext(), "此条在Mobile_FMT中未配置，请联系管理员", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Intent intent = new Intent(getActivity(), Class.forName("com.efounder.RNTaskActivity"));
                        intent.putExtra("status", "");
                        intent.putExtra("args", (Serializable) map);
                        startActivity(intent);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        mRecyclerView.setAdapter(adapter);
        return root;

    }

    /**
     * 请求数据
     *
     * @param paging true表示分页加载，false为刷新
     */
    private void getTaskData(final boolean paging) {
        Log.d("getTaskData", "begin-->");
        EFHttpRequest httpRequest = new EFHttpRequest(AppContext.getInstance().getApplicationContext());
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
            @Override
            public void onRequestSuccess(int requestCode, String response) {
                if (response.equals("")) {
                    //中铁工专用，其他请注释掉
                    mData.clear();
                    Task task = new Task("", "网上报销", "", taskDataItem0, "");
                    Task task1 = new Task("", "OA办公", "", taskDataItem1, "");
                    Task task2 = new Task("", "资金系统", "", taskDataItem2, "");
                    mData.add(0, task);
                    mData.add(1, task1);
                    mData.add(2, task2);
                    adapter.notifyDataSetChanged();


                    EnvironmentVariable.setProperty("Badge_Task_Pending", getBadgeNum() + "");
                    EventBus.getDefault().post(new UpdateBadgeViewEvent(-3 + "", (byte) 2));
                    mSrl.finishRefresh();
                    mSrl.finishLoadMore();
                } else {
                    try {
                        if (page == 0 || !paging) {
                            mData.clear();
                            Task task = new Task("", "网上报销", "", taskDataItem0, "");
                            Task task1 = new Task("", "OA办公", "", taskDataItem1, "");
                            Task task2 = new Task("", "资金系统", "", taskDataItem2, "");
                            mData.add(0, task);
                            mData.add(1, task1);
                            mData.add(2, task2);
                        }


                        JSONObject responseObject = new JSONObject(response);
                        String taskList = responseObject.getString("TaskList");
                        if (taskList.startsWith("{") || taskList.startsWith("[")) {
                            JSONArray taskListArray = responseObject.getJSONArray("TaskList");
                            if (taskListArray != null) {
                                if (paging)
                                    page++;
                                for (int i = 0; i < taskListArray.length(); i++) {
                                    Task task = new Task();
                                    task.setTitle((taskListArray.getJSONObject(i).getString("FLOW_MC")));
                                    task.setIcon((taskListArray.getJSONObject(i).getString("FlowIcon")));
                                    try {
                                        task.setInfo((taskListArray.getJSONObject(i).getString("FLOW_DES")));
                                    } catch (JSONException e) {
                                        task.setInfo("");
                                    }
                                    task.setId(taskListArray.getJSONObject(i).getString("FLOW_ID"));
                                    task.setTodoNum((taskListArray.getJSONObject(i).getInt("TASK_PENDING_COUNT")));
                                    mData.add(task);
                                }
                            }
                        }

                        adapter.notifyDataSetChanged();
                        EnvironmentVariable.setProperty("Badge_Task_Pending", getBadgeNum() + "");
                        EventBus.getDefault().post(new UpdateBadgeViewEvent(-3 + "", (byte) 2));
                        mSrl.finishRefresh();
                        mSrl.finishLoadMore();
                    } catch (JSONException e) {
                        e.printStackTrace();
                        //ToastUtil.showToast(getActivity(), "没有更多数据了");
                        mSrl.finishRefresh();
                        mSrl.finishLoadMore();
                    }
                }
            }

            @Override
            public void onRequestFail(int requestCode, String message) {
                //中铁工专用，其他请注释掉
                mData.clear();
                Task task = new Task("", "网上报销", "", taskDataItem0, "");
                Task task1 = new Task("", "OA办公", "", taskDataItem1, "");
                Task task2 = new Task("", "资金系统", "", taskDataItem2, "");
                mData.add(0, task);
                mData.add(1, task1);
                mData.add(2, task2);
                adapter.notifyDataSetChanged();
                EnvironmentVariable.setProperty("Badge_Task_Pending", getBadgeNum() + "");
                EventBus.getDefault().post(new UpdateBadgeViewEvent(-3 + "", (byte) 2));
                mSrl.finishRefresh();
                mSrl.finishLoadMore();
            }
        });
        if (null != stubObject) {
            Hashtable stubTable = stubObject.getStubTable();
            Object addwhere = stubTable.get("ADDWHERE");
            if (null != addwhere) {
                URL2 = ",PAGING_SHOWNUM=10,UserName='" + EnvironmentVariable.getUserName() + "',ADDWHERE='" + addwhere + "'}}";
            }
        }
        /***
         * 分页加载
         */
        if (paging) {
            //中铁工专用，其他请注释掉
            httpRequest.httpGet(URL1 + page + URL2);
        } else {
            //中铁工专用，其他请注释掉
            httpRequest.httpGet(URL1 + 0 + URL2);
        }

    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onSolveEventMessage(TaskRefreshEvent event) {
//        		getTaskData(false);
        getTGBadgeNum();//中铁工专用，其他请注释掉
    }

    /**
     * 获取TG的报销和OA的角标数
     */
    private void getTGBadgeNum() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String className = "sy.petrochina.zsytg.utils.JExterInterface";
                    ClassLoader loader = Thread.currentThread().getContextClassLoader();
                    Class<?> clazz = loader.loadClass(className);
                    Method method = clazz.getMethod("getTodoCountForApp");
                    String ob = (String) method.invoke(clazz.newInstance(), new Object[]{});
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(ob);
                    if (jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW") != null &&
                            !jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW").equals("")) {
                        taskDataItem0 = Integer.valueOf(jsonObject.getJSONObject("TaskDataItem0").getString("COUNT_ROW"));
                        taskDataItem1 = Integer.valueOf(jsonObject.getJSONObject("TaskDataItem1").getString("COUNT_ROW"));
                        taskDataItem2 = Integer.valueOf(jsonObject.getJSONObject("TaskDataItem2").getString("COUNT_ROW"));

                        Log.d("wwl_test", "获取铁工角标完成");
                    }
                    handler.sendEmptyMessage(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取总的角标数量
     *
     * @return 角标数
     */
    private int getBadgeNum() {
        int badgeNum = 0;
        for (int i = 0; i < mData.size(); i++) {
            badgeNum += mData.get(i).getTodoNum();
        }
        return badgeNum;
    }

    @Override
    public void onVisible() {
        if (!hasLoadData) {
            linearLayout.setBackgroundResource(R.drawable.write);
        }
    }

    @Override
    public void onTabBottomActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("", "-------onTabBottomActivityResult:" + TAG);
        if (resultCode == Activity.RESULT_OK) {
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
